import { reqIdentifyingCode, reqRegister, reqLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
// home模块的小仓库
// state：仓库存储数据的地方
const state = {
    IdentifyingCode: '',
    token: getToken(),
    UserInfo: {}
}
// mutations:修改state的唯一手段
const mutations = {
    IdentifyingCode(state, val) {
        state.IdentifyingCode = val
    },
    Login(state, val) {
        state.token = val
    },
    UserInfo(state, val) {
        state.UserInfo = val
    },
    Logout(state, val) {
        state.token = ''
        state.UserInfo = {}
        removeToken()
    }
}
// actions：处理action，可以书写自己的业务逻辑，也可以处理异步
const actions = {
    async IdentifyingCode({ commit }, phone) {
        let result = await reqIdentifyingCode(phone)
        if (result.code == 200) {
            commit('IdentifyingCode', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async Register({ commit }, data) {
        let result = await reqRegister(data)
        console.log(result)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async Login({ commit }, data) {
        let result = await reqLogin(data)
        console.log(result)
        if (result.code == 200) {
            commit('Login', result.data.token)
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async UserInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            // console.log(result.data)
            commit('UserInfo', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    async Logout({ commit }) {
        let result = await reqLogout()
        if (result.code == 200) {
            commit('Logout', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('fail'))
        }

    }
}
// getters:理解为计算属性，用于简化仓库数据，让组件获取仓库的数据更加方便
const getters = {

}
export default ({
    state,
    mutations,
    actions,
    getters
})